import datetime
import json

from django.shortcuts import render,redirect
from django.shortcuts import HttpResponse
from django.views.decorators.csrf import csrf_exempt

from cin_tic_sal import models
from cinema_app import models as cinmodel
from movie_app import models as mov_model
from user_app import models as user_model
from django.contrib.auth import login   #用户登录维持
# Create your views here.


# def uploadImg(request):
#
#     if request.method == 'POST':
#         new_img = IMG(
#             img=request.FILES.get('img'),
#             name=request.FILES.get('img').name
#         )
#         new_img.save()
#     return render(request, 'uploading.html')
#
# @csrf_exempt
# def upimage(request):      #图片上传接口
#     uid = request.COOKIES.get('id')
#     obj = models.User_info.objects.get(id = uid)
#     img = request.FILES.get('file')
#     #保存图片
#     img_name = uuid.uuid4().get_hex()
#     img_path = os.path.join('../static/media/user_photo/', img_name)
#     with open(img_path, 'ab') as fp:
#         # 如果上传的图片非常大， 那么通过 img对象的 chunks() 方法 分割成多个片段来上传
#         for chunk in img.chunks():
#             fp.write(chunk)
#     obj.H_photo = img_path
#     obj.save()
#     msg="上传成功"
#     res = HttpResponse(json.dumps(msg),content_type="application/json")
#     return res
@csrf_exempt
def buytic(request,sessionid):
    if request.method == "POST":
        session_id =request.POST.get("session_id")
        seat = request.POST.get('seat')
        try:
            user = user_model.User_info.objects.get(id = request.session['user_id'])
            count = user_model.User_info.objects.all()
            count = len(count)
            order = models.Order_info(user_account=user.account)
            order.seat =seat
            order.id = count+1
            order.session_id = int(session_id)
            order.pay_way =1
            order.order_time = datetime.datetime.now()
            order.save()
            msg = {'msg':"success"}
        except Exception as e:
            print(e)
            msg = {'msg':'fail'}
        return HttpResponse(json.dumps(msg),content_type="application/json")

    else:
        #利用sessionid寻找场次
        session = cinmodel.Session_info.objects.get(id=sessionid)
        movie = mov_model.Movie_info.objects.get(id=session.movie_id)
        content = {}
        content["mov_name"] = movie.name
        content["session_time"] = session.be_time
        content["price"] = session.price
        seat = []
        #已经订票位置 "1-2,1-3"
        #寻找该场次所有座位信息
        #try:
        order_list = models.Order_info.objects.filter(session_id=session.id)
        if(len(order_list) == 0):
            seat = str(seat)
        else:
            for order in order_list:
                list = order.seat.split(',')
                for item in list:
                    seat.append(item)
            seat = str(seat)
            seat=seat.replace("-","_")
        content["unavailable"] =seat
        return render(request,"order_page.html",content)